package com.leoandroid.tool.toolsbox.new

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.leoandroid.tool.toolsbox.adapter.ChengYuAdapter
import com.leoandroid.tool.toolsbox.largeread.databinding.ActivityChengyuBinding
import com.leoandroid.tool.toolsbox.net.NetCallBack
import com.leoandroid.tool.toolsbox.net.NetRequest
import org.json.JSONObject

class ChengYuActivity:AppCompatActivity() {

    var bindingF:ActivityChengyuBinding?=null
    val binding get() = bindingF!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindingF = ActivityChengyuBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.includeTitle.titleTv.text = "成语接龙"
        binding.includeTitle.backIv.setOnClickListener {
            finish()
        }
        binding.recycleview.layoutManager = LinearLayoutManager(this)
        binding.searchTv.setOnClickListener {
            val str = binding.edit.text
            if(TextUtils.isEmpty(str)){
              Toast.makeText(this,"请输入内容",Toast.LENGTH_SHORT).show()
            } else {
                var content = str[str.lastIndex].toString()
                val url = "http://apis.juhe.cn/idiomJie/query?key=add03906b0595b711ea390b1a5fe6ca5&wd=$content"
                NetRequest.asyncGet(url,object : NetCallBack {
                    override fun onFailure(code: Int, e: Throwable?) {
                        Log.d("pppppp","加载失败》"+e.toString())
                    }

                    override fun onSuccess(json: JSONObject?) {
                        val string = json?.getString("result")
                        val jsonResult = JSONObject(string)
                        val data = jsonResult.getString("data")
                        val type = object : TypeToken<ArrayList<String>>() {}.type
                        val fromJson = Gson().fromJson<ArrayList<String>>(data, type)
                        //    val chengyu = Gson().fromJson(jsonResult,ChengYuBean::class.java)
                        runOnUiThread {
                            val adapter = ChengYuAdapter(this@ChengYuActivity,fromJson)
                            binding.recycleview.adapter = adapter
                        }
                    }

                })
            }

        }

    }
}